package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class PurchaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookId = request.getParameter("id");
        Book book = BookDB.getBookById(bookId);

        if (book != null) {
            HttpSession session = request.getSession();
            List<Book> cart = (List<Book>) session.getAttribute("cart");

            if (cart == null) {
                cart = new ArrayList<>();
                session.setAttribute("cart", cart);
            }

            cart.add(book);

            // 将Session的ID保存到Cookie中
            String sessionId = session.getId();
            Cookie sessionCookie = new Cookie("JSESSIONID", sessionId);
            sessionCookie.setMaxAge(30 * 60); // 设置Cookie存活时间为30分钟
            response.addCookie(sessionCookie);
        }

        response.sendRedirect("BookServlet");
    }
}